<?php
declare(strict_types=1);

namespace WebApp\lib\db\redis;

use Closure;
use Redis;
use Throwable;

/**
 * Class Table
 * @package txz\common\third_lib\model\lib
 */
class NormalRedisDriver extends RedisDriver
{
    public function __construct(RedisConfig $config)
    {
        parent::__construct($config);
    }

    public function get(string $key) {
        return function(Redis $conn)use($key){
            return $conn->get($key);
        };
    }

    public function set(string $key, string $val) {
        return function(Redis $conn)use($key, $val){
            return $conn->set($key, $val);
        };
    }

    public function del(string $key) {
        return function(Redis $conn)use($key){
            return $conn->del($key);
        };
    }

    /**
     * @param string $table
     * @return mixed
     */
    public function hGetAll(string $table)
    {
        return function(Redis $conn)use($table){
            return $conn->hGetAll($table);
        };
    }

    /**
     * @param string $key
     * @param string $val
     * @param int $ttl
     * @return Closure
     */
    public function setEx(string $key, string $val, int $ttl)
    {
        return function(Redis $conn)use($key, $val, $ttl){
            return $conn->setex($key, $ttl, $val);
        };
    }

    /**
     * @param string $key
     * @return Closure
     */
    public function keys(string $key)
    {
        return function(Redis $conn)use($key){
            return $conn->keys($key . "*");
        };
    }

    /**
     * @param string $key
     * @return Closure
     */
    public function all(string $key)
    {
        return function(Redis $conn)use($key){
            return $conn->a($key . "*");
        };
    }

    /**
     * @param string $table
     * @param string $key
     * @return mixed
     */
    public function hGet(string $table, string $key)
    {
        return function(Redis $conn)use($table, $key){
            return $conn->hGet($table, $key);
        };
    }

    /**
     * @param string $table
     * @param string $key
     * @param string $val
     * @return Closure
     */
    public function hSet(string $table, string $key, string $val)
    {
        return function(Redis $conn)use($table, $key, $val){
            return $conn->hSet($table, $key, $val);
        };
    }

    public function getCon(): Redis
    {
        $conn = new Redis();
        $conn->connect($this->config->getHost(), $this->config->getPort());

        return $conn;
    }

    /**
     * @param $conn
     * @param Throwable $e
     */
    public function catchErr(&$conn, Throwable $e)
    {
        tracker(E, $e->getMessage());
        tracker(D, $e->getTraceAsString());
    }

    public function getTryCount(): int
    {
        return 1;
    }
}
